package com.youxin.foundation.utils.locks;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 全局锁封装
 * @author yingde.cao
 *
 */
public class LockObject {

	private static Lock lock = new ReentrantLock();
	/**
	 * 全局锁方法,整个应用程序锁,确保锁住的时间很少
	 * @param lockStatement
	 */
	public static void lockApplication(LockStatement lockStatement) {
		lock.lock();
		try {
			lockStatement.execute();
		} finally {
			lock.unlock();
		}
	}
	
	/**
	 * 类内部锁封装
	 * @param lockStatement
	 */
	public static void lock(LockStatement lockStatement) {
		Lock innerLock = new ReentrantLock();
		innerLock.lock();
		try {
			lockStatement.execute();
		} finally {
			innerLock.unlock();
		}
	}
	
	/**
	 * 定义接口执行的方法
	 * @author yingde.cao
	 *
	 */
	@FunctionalInterface
	public static interface LockStatement{
		/**
		 * 锁内运行方法
		 */
	    void execute();
	}
	
}
